package com.ruoyi.article.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.article.domain.ZLabel;
import com.ruoyi.article.domain.ZPraiseLog;
import com.ruoyi.article.domain.ZRelationArticleLabel;
import com.ruoyi.article.domain.vo.AppUserInfo;
import com.ruoyi.article.domain.vo.ArticleParam;
import com.ruoyi.article.mapper.ZLabelMapper;
import com.ruoyi.article.service.IZBugService;
import com.ruoyi.article.service.IZPraiseLogService;
import com.ruoyi.article.service.IZRelationArticleLabelService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.ruoyi.article.mapper.ZArticleMapper;
import com.ruoyi.article.domain.ZArticle;
import com.ruoyi.article.service.IZArticleService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 文章Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-24
 */
@Service
public class ZArticleServiceImpl extends ServiceImpl<ZArticleMapper,ZArticle> implements IZArticleService
{
    @Autowired
    private ZArticleMapper zArticleMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private ZLabelMapper labelMapper;
    @Autowired
    private ZRelationArticleLabelServiceImpl ZRelationArticleLabelServiceImpl;

    @Autowired
    private IZArticleService zArticleService;
    @Autowired
    private IZRelationArticleLabelService zRelationArticleLabelService;
    @Autowired
    private IZPraiseLogService zPraiseLogService;


    /**
     * 查询文章
     * 
     * @param id 文章主键
     * @return 文章
     */
    @Override
    public ZArticle selectZArticleById(Long id)
    {
        return zArticleMapper.selectZArticleById(id);
    }

    /**
     * 查询文章列表
     * 
     * @param zArticle 文章
     * @return 文章
     */
    @Override
    public List<ZArticle> selectZArticleList(ZArticle zArticle)
    {
        return zArticleMapper.selectZArticleList(zArticle);
    }

    /**
     * 新增文章
     * 
     * @param zArticle 文章
     * @return 结果
     */
    @Override
    @Transactional
    public int insertZArticle(ZArticle zArticle)
    {
        zArticle.setCreateTime(DateUtils.getNowDate());
        zArticle.setAuthorId(SecurityUtils.getUserId());
        zArticle.setAuthor(SecurityUtils.getUsername());


        //维护文章与文章标签的关系
        List<ZLabel> zLabels = null;
        if (ObjectUtils.isEmpty(zArticle.getLabelIds())){
            throw new ServiceException("标签id为空");
        }
        //查询当前文章的标签
        zLabels = labelMapper.selectBatchIds(zArticle.getLabelIds());
        if (zLabels.size() != zArticle.getLabelIds().size()){
            throw new ServiceException("标签id参数错误");
        }
        StringBuilder articleLabel = new StringBuilder();
        for (ZLabel zLabel : zLabels) {
            //如果字符串长度不等于0，即articleLabel已经存在字符串
            if (articleLabel.length() != 0){
                articleLabel.append(","+zLabel.getName());
            }else {
                articleLabel.append(zLabel.getName());
            }
        }
        String string = articleLabel.toString();
        zArticle.setArticleLabel(string);
        zArticleMapper.insert(zArticle);
        Long articleId = zArticle.getId();
        ArrayList<ZRelationArticleLabel> zRelationArticleLabels = new ArrayList<>();
        for (ZLabel zLabel : zLabels) {
            ZRelationArticleLabel zRelationArticleLabel = new ZRelationArticleLabel();
            zRelationArticleLabel.setArticleId(articleId);
            zRelationArticleLabel.setLabelId(zLabel.getId());
            zRelationArticleLabel.setArticleTitle(zArticle.getTitle());
            zRelationArticleLabel.setLabelName(zLabel.getName());
            //0已发布，1待发布
            zRelationArticleLabel.setArticleStatus("1");
            zRelationArticleLabels.add(zRelationArticleLabel);
        }
        return ZRelationArticleLabelServiceImpl.saveBatch(zRelationArticleLabels) ? 1 : -1;
    }

    /**
     * 修改文章
     * @param zArticle 文章
     * @return 结果
     */
    @Override
    @Transactional
    public int updateZArticle(ZArticle zArticle) throws UnknownHostException {

        if (!zArticle.getStatus().equals("1")){
            SysNotice sysNotice = new SysNotice();
            if (zArticle.getStatus().equals("0")){
                //已发布
                sysNotice.setNoticeContent("通过");
            }
            if (zArticle.getStatus().equals("2")){
                //已发布
                sysNotice.setNoticeContent("不通过");
            }
            //新增私人通知
            sysNotice.setNoticeTitle("文章审核");
            sysNotice.setNoticeType("3");
            sysNotice.setStatus("0");
            sysNotice.setUserId(zArticle.getAuthorId());
            noticeService.insertNotice(sysNotice);
        }


        Pattern pattern = Pattern.compile("src=\"([^\"]+)\"");
        String content = zArticle.getContent();
        if (!ObjectUtils.isEmpty(content)) {
            StringBuffer result = getStringBuffer(pattern, content);
            zArticle.setContent(result.toString());
        }

        //得到需要修改的标签id集合
        List<Long> labelIds = zArticle.getLabelIds();
        if (!ObjectUtils.isEmpty(labelIds)) {
            //意味着文章与标签的对应关系也需要修改  先删除后新增
            LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(!ObjectUtils.isEmpty(zArticle.getId()),ZRelationArticleLabel::getArticleId,zArticle.getId());
            ZRelationArticleLabelServiceImpl.remove(wrapper);

            List<ZLabel> zLabels = labelMapper.selectBatchIds(labelIds);

            ArrayList<ZRelationArticleLabel> zRelationArticleLabels = getArticleLabels(zArticle, zLabels, labelIds);
            ZRelationArticleLabelServiceImpl.saveBatch(zRelationArticleLabels);

            zArticle.setUpdateTime(DateUtils.getNowDate());

            StringBuilder articleLabel = new StringBuilder();
            for (ZLabel zLabel : zLabels) {
                //如果字符串长度不等于0，即articleLabel已经存在字符串
                if (articleLabel.length() != 0){
                    articleLabel.append(","+zLabel.getName());
                }else {
                    articleLabel.append(zLabel.getName());
                }
            }
            String string = articleLabel.toString();
            zArticle.setArticleLabel(string);
        }

        //文章分配时 更新ZRelationArticleLabel表中ArticleStatus字段的状态0已发布，1待发布
        if (!ObjectUtils.isEmpty(zArticle.getArticleStatus())){
            //查询当前文章所分配的标签数据
            LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(!ObjectUtils.isEmpty(zArticle.getId()),ZRelationArticleLabel::getArticleId,zArticle.getId());
            ZRelationArticleLabel zRelationArticleLabel = new ZRelationArticleLabel();
            zRelationArticleLabel.setArticleStatus(zArticle.getArticleStatus());
            ZRelationArticleLabelServiceImpl.update(zRelationArticleLabel,wrapper);
        }

        return zArticleMapper.updateById(zArticle);
    }

    private static StringBuffer getStringBuffer(Pattern pattern, String content) throws UnknownHostException {
        Matcher matcher = pattern.matcher(content);
        //获取本机ip地址
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            // 获取捕获到的原路径   src="/dev-api/profile/upload/2025/01/26/稿定设计-3_20250126220851A001.jpg"
            String oldPath = matcher.group(1);
            if (!oldPath.startsWith("http://")) {
                // 只有当原路径不包含http://时才进行拼接和替换操作
                String newPath = "http://" + hostAddress  + oldPath;
                matcher.appendReplacement(result, "src=\"" + newPath + "\"");
            } else {
                // 原路径已包含http://localhost，直接添加到结果字符串缓冲区，保持不变
                matcher.appendReplacement(result, matcher.group(0));
            }
        }
        matcher.appendTail(result);
        return result;
    }

    private static ArrayList<ZRelationArticleLabel> getArticleLabels(ZArticle zArticle, List<ZLabel> zLabels, List<Long> labelIds) {
        if (zLabels.size() != labelIds.size()){
            throw new ServiceException("标签id参数错误");
        }

        //新增relationArticleLabel数据
        Long articleId = zArticle.getId();
        ArrayList<ZRelationArticleLabel> zRelationArticleLabels = new ArrayList<>();
        for (ZLabel zLabel : zLabels) {
            ZRelationArticleLabel zRelationArticleLabel = new ZRelationArticleLabel();
            zRelationArticleLabel.setArticleId(articleId);
            zRelationArticleLabel.setLabelId(zLabel.getId());
            zRelationArticleLabel.setArticleTitle(zArticle.getTitle());
            zRelationArticleLabel.setLabelName(zLabel.getName());
            zRelationArticleLabel.setArticleStatus(zArticle.getStatus());
            //zRelationArticleLabel.setArticleStatus(zArticle.getArticleStatus());
            zRelationArticleLabels.add(zRelationArticleLabel);
        }
        return zRelationArticleLabels;
    }

    /**
     * 批量删除文章
     * 
     * @param ids 需要删除的文章主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteZArticleByIds(Long[] ids)
    {
        zArticleMapper.deleteBatchIds(Arrays.asList(ids));
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ZRelationArticleLabel::getArticleId,ids);

        return ZRelationArticleLabelServiceImpl.remove(wrapper) ? 1 : -1;
    }

    /**
     * 删除文章信息
     * 
     * @param id 文章主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteZArticleById(Long id)
    {
        zArticleMapper.deleteZArticleById(id);
        //删除文章和标签的对应关系数据
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getArticleId,id);

        return ZRelationArticleLabelServiceImpl.remove(wrapper) ? 1 : -1;
    }

    @Override
    public List<ZArticle> selectArticleAll(ZArticle zArticle) {
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        //将yyyy-MM-dd HH:mm:ss转成yyyy-MM-dd进行模糊查询
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");

        //判断前端传递的是否是标签的id
        if (Objects.nonNull(zArticle.getLabelId())){
            return getzArticles(zArticle, queryWrapper, targetFormat);
        }

        if (Objects.nonNull(zArticle.getSendTime())){
            String format = targetFormat.format(zArticle.getSendTime());
            queryWrapper.like(ZArticle::getSendTime,format);
        }

        startPage();
        queryWrapper.like(Objects.nonNull(zArticle.getTitle()),ZArticle::getTitle,zArticle.getTitle());
        queryWrapper.like(Objects.nonNull(zArticle.getAuthor()),ZArticle::getAuthor,zArticle.getAuthor());
        queryWrapper.eq(Objects.nonNull(zArticle.getStatus()),ZArticle::getStatus,zArticle.getStatus());
        queryWrapper.eq(Objects.nonNull(zArticle.getIsTop()),ZArticle::getIsTop,zArticle.getIsTop());
        List<ZArticle> list = zArticleService.list(queryWrapper);
        return list;
    }

    @Override
    @Transactional
    public ZArticle getByIdArticle(Long id) {
        ZArticle article = getById(id);
        //当前文章浏览量+1
        article.setSee(article.getSee()+1);
        updateById(article);
        //查询当前文章所属的标签（查询文章标签关系表）
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Objects.nonNull(article.getId()),ZRelationArticleLabel::getArticleId,article.getId());
        List<ZRelationArticleLabel> relationLabelList = ZRelationArticleLabelServiceImpl.list(wrapper);

        if (ObjectUtils.isEmpty(relationLabelList)){
            throw new ServiceException("文章未分配标签::"+article.getTitle());
        }
        //得到当前文章的所有标签id
        List<Long> LabelIds = relationLabelList.stream().map(ZRelationArticleLabel::getLabelId).collect(Collectors.toList());
        //得到所有标签数据
        List<ZLabel> zLabels = labelMapper.selectList(null);

        //当前文章的所有标签的id集合
        article.setLabelIds(LabelIds);
        article.setLabels(zLabels);
        return article;
    }

    @Override
    public List<ZArticle> selectTopArticle() {
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZArticle::getIsTop, 0)
                .eq(ZArticle::getStatus,'0');
        List<ZArticle> list = list(queryWrapper);
        List<ZArticle> collect = list.stream().limit(6).collect(Collectors.toList());
        return collect;
    }

    @Override
    public TableDataInfo getArticleListByLabelId(ArticleParam articleParam) {
        //这里的id是标签id
        Long id = articleParam.getId();
        int pageSize = articleParam.getPageSize();
        int pageCurrent = articleParam.getPageCurrent();
        if (id == null){
            throw new ServiceException("标签id为空");
        }
        //查询当前标签下状态为已发布（0已发布，1待发布）的所有文章，
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getLabelId,id);
        wrapper.eq(ZRelationArticleLabel::getArticleStatus,"0");
        IPage<ZRelationArticleLabel> RelationArticleLabelPage = ZRelationArticleLabelServiceImpl.page(new Page<>(pageCurrent,pageSize), wrapper);
        List<ZRelationArticleLabel> labelList = RelationArticleLabelPage.getRecords();
        List<Long> articleId = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());
        List<ZArticle> zArticles = zArticleMapper.selectBatchIds(articleId);


        //封装文章作者用户头像
        for (ZArticle zArticle : zArticles) {
            Long authorId = zArticle.getAuthorId();
            SysUser sysUser = userService.selectUserById(authorId);
            zArticle.setAuthorUrl(sysUser.getAvatar());
        }

        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(zArticles);
        dataInfo.setTotal(RelationArticleLabelPage.getTotal());
        return dataInfo;
    }

    @Override
    public List<ZArticle> selectArticleByTitle(String title,Integer pageCurrent,Integer pageSize) {
        // 计算偏移量
        int offset = (pageCurrent - 1) * pageSize;
        List<ZArticle> zArticles = zArticleMapper.selectListByLikeTitle("%"+title+"%",offset,pageSize);
        //封装文章作者用户头像
        for (ZArticle zArticle : zArticles) {
            Long authorId = zArticle.getAuthorId();
            SysUser sysUser = userService.selectUserById(authorId);
            zArticle.setAuthorUrl(sysUser.getAvatar());
        }
        return zArticles;
    }

    @Override
    public long selectCountByTitle(String title) {
        Long total = zArticleMapper.countByTitle("%"+title+"%");
        return total;
    }

    @Override
    public Long insertZArticleAll(ZArticle zArticle) throws UnknownHostException {
        Long id = zArticle.getId();
        if (ObjectUtils.isEmpty(id)){
            insertZArticle(zArticle);
            return zArticle.getId();
        }
        updateZArticle(zArticle);
        return zArticle.getId();
    }

    @Override
    public TableDataInfo listArticleByUserId(ZArticle zArticle) {
        Long userId = getLoginUser().getUserId();
        Page<ZArticle> zArticlePage = new Page<>(zArticle.getPageNum(),zArticle.getPageSize());
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(zArticle.getTitle()),ZArticle::getTitle, zArticle.getTitle());
        queryWrapper.eq(ZArticle::getAuthorId, userId);
        Page<ZArticle> zArticlePage1 = zArticleMapper.selectPage(zArticlePage, queryWrapper);
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows(zArticlePage1.getRecords());
        dataInfo.setTotal(zArticlePage1.getTotal());
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        return dataInfo;
    }

    //查询当前用户所收藏的文章列表
    @Override
    public TableDataInfo listArticleCollect(ZArticle zArticle) {
        Long userId = getLoginUser().getUserId();
        Page<ZPraiseLog> zArticlePage = new Page<>(zArticle.getPageNum(),zArticle.getPageSize());
        LambdaQueryWrapper<ZPraiseLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZPraiseLog::getUserId, userId)
                //文章收藏
                .eq(ZPraiseLog::getStatus,'1');
        Page<ZPraiseLog> page = zPraiseLogService.page(zArticlePage, queryWrapper);
        //得到当前用户所收藏文章的id集合
        List<Long> articleIds = page.getRecords().stream().map(ZPraiseLog::getArticleId).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(articleIds)){{
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setRows(new ArrayList<>());
            dataInfo.setTotal(0);
            dataInfo.setCode(HttpStatus.SUCCESS);
            dataInfo.setMsg("查询成功");
            return dataInfo;
        }}
        List<ZArticle> zArticles = zArticleMapper.selectBatchIds(articleIds);

        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows(zArticles);
        dataInfo.setTotal(page.getTotal());
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        return dataInfo;
    }

    @Override
    public TableDataInfo getArticleList(ArticleParam articleParam) {
        int pageSize = articleParam.getPageSize();
        int pageCurrent = articleParam.getPageCurrent();
        //查询当前标签下状态为已发布（0已发布，1待发布）的所有文章
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getArticleStatus,"0");
        IPage<ZRelationArticleLabel> RelationArticleLabelPage = ZRelationArticleLabelServiceImpl.page(new Page<>(pageCurrent,pageSize), wrapper);
        List<ZRelationArticleLabel> labelList = RelationArticleLabelPage.getRecords();
        List<Long> articleId = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());
        List<ZArticle> zArticles = zArticleMapper.selectBatchIds(articleId);


        //封装文章作者用户头像
        for (ZArticle zArticle : zArticles) {
            Long authorId = zArticle.getAuthorId();
            SysUser sysUser = userService.selectUserById(authorId);
            zArticle.setAuthorUrl(sysUser.getAvatar());
        }

        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(zArticles);
        dataInfo.setTotal(RelationArticleLabelPage.getTotal());
        return dataInfo;
    }

    @Override
    public List<ZArticle> listArticleByLabelTop(Long id) {
        //查询当前标签的文章
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getLabelId, id);
        List<ZRelationArticleLabel> labelList = ZRelationArticleLabelServiceImpl.list(wrapper);
        //得到当前标签下的所有文章id
        List<Long> articleIds = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());

        //查询当前标签下状态为已发布（0已发布，1待发布）的所有文章
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZArticle::getIsTop, 0)
                .eq(ZArticle::getStatus,'0')
                .in(Objects.nonNull(articleIds),ZArticle::getId,articleIds);
        List<ZArticle> list = list(queryWrapper);
        List<ZArticle> collect = list.stream().limit(6).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<ZArticle> getTopArticle() {
        return  selectTopArticle();
    }

    @Override
    public List<ZArticle> getNewArticle() {
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ZArticle::getSendTime)
                .eq(ZArticle::getStatus,'0');
        List<ZArticle> list = list(queryWrapper);
        List<ZArticle> collect = list.stream().limit(6).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<ZArticle> getArticleClassifyTop(Long id) {
        //查询文章标签关系表，得到当前标签的文章
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getLabelId, id)
                .eq(ZRelationArticleLabel::getArticleStatus,"0");
        List<ZRelationArticleLabel> labelList = ZRelationArticleLabelServiceImpl.list(wrapper);
        //得到文章id集合
        List<Long> articleIds = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());
        //查询文章表，得到当前标签下的所有文章
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Objects.nonNull(articleIds),ZArticle::getId,articleIds)
                .eq(ZArticle::getStatus,"0")
                .eq(ZArticle::getIsTop,"0");
        List<ZArticle> zArticles = list(queryWrapper).stream().limit(6).collect(Collectors.toList());
        return zArticles;
    }

    @Override
    public List<ZArticle> getClassifyArticle(ArticleParam articleParam) {
        Long id = articleParam.getId();

        //查询文章标签关系表，得到当前标签的文章
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getLabelId, id)
                .eq(ZRelationArticleLabel::getArticleStatus,"0");
        List<ZRelationArticleLabel> labelList = ZRelationArticleLabelServiceImpl.page(new Page<>(articleParam.getPageCurrent(),articleParam.getPageSize()),wrapper).getRecords();
        if (ObjectUtils.isEmpty(labelList)){
            return new ArrayList<ZArticle>();
        }
        //得到文章id集合
        List<Long> articleIds = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());
        //查询文章表，得到当前标签下的所有文章
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Objects.nonNull(articleIds),ZArticle::getId,articleIds)
                .eq(ZArticle::getStatus,"0");
        List<ZArticle> zArticles = list(queryWrapper);
        return zArticles;
    }

    @Override
    public AppUserInfo getByIdArticleAuthor(Long articleId) {
        ZArticle article = getById(articleId);
        if (!ObjectUtils.isEmpty(article)){
            String author = article.getAuthor();
            Long authorId = article.getAuthorId();
            SysUser sysUser = userService.selectUserById(authorId);
            if (!ObjectUtils.isEmpty(sysUser)){
                AppUserInfo appUserInfo = new AppUserInfo();
                appUserInfo.setUserId(authorId);
                appUserInfo.setUserName(author);
                appUserInfo.setAvatar(sysUser.getAvatar());
                return appUserInfo;
            }
        }
        return null;
    }

    @Override
    public List<ZArticle> getArticleListById(Long id) {
        LambdaQueryWrapper<ZArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZArticle::getAuthorId,id);
        List<ZArticle> zArticles = list(queryWrapper);
        return zArticles;
    }

    @Override
    public Boolean updateArticleById(ZArticle zArticle) {
        ZArticle zArticle1 = getById(zArticle.getId());
        if (!ObjectUtils.isEmpty(zArticle1)){
            return updateById(zArticle);
        }
        return false;
    }

    private List<ZArticle> getzArticles(ZArticle zArticle, LambdaQueryWrapper<ZArticle> queryWrapper, SimpleDateFormat targetFormat) {
        //查询标签文章关系表，得到此标签下的所有标签
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZRelationArticleLabel::getLabelId, zArticle.getLabelId());
        List<ZRelationArticleLabel> labelList = zRelationArticleLabelService.list(wrapper);
        //判断是否存在相同数据(可能存在两个（或多个）相同的标签对应两个（或多个）相同的文章，数据重复)
        long size = labelList.size();
        long count = labelList.stream().distinct().count();
        if (size != count){
            throw new ServiceException("标签和文章关系表中存在相同数据");
        }
        List<Long> articleIds = labelList.stream().map(ZRelationArticleLabel::getArticleId).collect(Collectors.toList());
        startPage();
        queryWrapper.in(Objects.nonNull(articleIds),ZArticle::getId,articleIds);
        queryWrapper.like(Objects.nonNull(zArticle.getTitle()),ZArticle::getTitle, zArticle.getTitle());
        queryWrapper.eq(Objects.nonNull(zArticle.getStatus()),ZArticle::getStatus, zArticle.getStatus());
        if (Objects.nonNull(zArticle.getSendTime())){
            String format = targetFormat.format(zArticle.getSendTime());
            queryWrapper.like(ZArticle::getSendTime,format);
        }

        List<ZArticle> zArticles = zArticleService.list(queryWrapper);
        return zArticles;
    }



}
